package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.system.mapper.AppUserMapper;
import com.ruoyi.system.service.IAppUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class AppUserServiceImpl implements IAppUserService {
    @Resource
    private AppUserMapper appUserMapper;
    /**
     * 新增用户
     * @param appUser
     * @return
     */
    @Override
    public int insertAppUser(AppUser appUser) {
        return appUserMapper.insertAppUser(appUser);
    }

    /**
     * 通过用户名查询用户
     *
     * @param openid 用户名
     * @return 用户对象信息
     */
    @Override
    public AppUser selectAppUserByOpenid(String openid) {
        return appUserMapper.selectAppUserByOpenid(openid);
    }
    /**
     * 通过用户名查询用户
     *
     * @param username 用户名
     * @return 用户对象信息
     */
    @Override
    public AppUser selectAppUserByUserName(String username) {
        return appUserMapper.selectAppUserByUsername(username);
    }
    /**
     * 修改保存用户信息
     *
     * @param appUser 用户信息
     * @return 结果
     */
    @Override
    public int updateAppUser(AppUser appUser) {
        return appUserMapper.updateAppUser(appUser);
    }

    /**
     * 密码校验
     *
     * @param password 明文
     * @param salt     盐
     * @param hashPwd  密文
     * @return boolean
     */
    public boolean checkPassword(String password, String salt, String hashPwd) {
        return hashPwd.equals(DigestUtils.md5DigestAsHex(password.concat(salt).getBytes()));
    }

    @Override
    public boolean updateAppUserAvatar(String username, String url) {
        return appUserMapper.updateAppUserAvatar(username, url) > 0;
    }

    /**
     * 随即生成盐
     * 8位随机数
     *
     * @return salt 盐
     */
    private String generateSalt() {
        return RandomStringUtils.randomAlphanumeric(8);
    }

    public static void main(String[] args) {
        AppUserServiceImpl appUserService = new AppUserServiceImpl();
        String password = "123456";
        String salt = appUserService.generateSalt();
        System.out.printf("明文密码：%s%n", password);
        System.out.printf("盐：%s%n", salt);
        System.out.printf("密文密码：%s%n", DigestUtils.md5DigestAsHex(password.concat(salt).getBytes()));
    }
}
